mul
do I get an error message.) static
and gives a linker error instead of a compiler error. .
#include <iostream>
template<typename T>
struct traits1{
static T add(T a, T b) { return a+b; } /* default */
static T mul(T a, T b); /* no default */
};
template<>
struct traits1<int> {
static int add(int a, int b) { return a*b; }
/* static int mul(int a, int b) missing, please warn */
};
template<typename T>
struct traits2{
static T add(T a, T b);
static T mul(T a, T b);
};
template<>
int traits2<int>::add(int a, int b) { return a*b; }
/* traits2<int>::mul(int a, int b) missing, please warn */
int main()
{
std::cout << traits1<int>::add(40, 2) << "\n";
// error: mul is not a member of traits1<int>
//std::cout << traits1<int>::mul(40, 2) << "\n";
std::cout << traits2<int>::add(40, 2) << "\n";
// error: undefined reference to traits2<int>::mul(int, int)
//std::cout << traits2<int>::mul(40, 2) << "\n";
return 0;
}
1) Don't specialize the whole class if all you want is different behavior for one particular function. Specialize that function alone:
template<>
int traits1<int>::add(int a, int b) { return a*b; }
You can't make sure a specialization implements the all template methods, because they're unrelated.
2) You didn't provide a definition for traits2::mul
, so of course you get the linker error - the declarations is there.
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.