Is it possible to specialize a function (or a class at least) to select between constant (compile-time!) integer and all other arguments? And if so, it would be nice to specialize (enable_if) for specific constant values only.
In the example below this would mean output "var", "const", and "var", not three "var"s.
#include <type_traits>
#include <iostream>
using namespace std;
struct test
{
template <typename T>
test& operator=(const T& var) { cout << "var" << endl; return *this; }
template <int n> // enable_if< n == 0 >
test& operator=(int x) { cout << "const" << endl; return *this; }
};
int main()
{
test x;
x = "x";
x = 1;
int y = 55;
x = y;
return 0;
}
UPDATE: edited the code to emphasize that it has to be compile-time constant.
To get var, const, var
in your example you can do that.
struct test {
template <typename T>
test& operator=(const T& var) { cout << "var" << endl; return *this; }
test& operator=(int &&x) { cout << "const" << endl; return *this; }
};
It will work for all temporaries, but it will fail for:
const int yy = 55;
x = yy;
To make it work for such a case too you will need to add:
test& operator=(int &x) { cout << "var" << endl; return *this; }
test& operator=(const int &x) { cout << "const" << endl; return *this; }
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.