以下编译按预期运行和执行:
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <type_traits>
class Freaky {
public:
template<
typename UNSIGNED_TYPE,
typename std::enable_if<(sizeof(UNSIGNED_TYPE)>=sizeof(int)),int>::type X = 0
>
static UNSIGNED_TYPE copyThing(int x) ;
};
template<
typename UNSIGNED_TYPE,
typename std::enable_if<(sizeof(UNSIGNED_TYPE)>=sizeof(int)),int>::type X
>
UNSIGNED_TYPE Freaky::copyThing(int x) {
UNSIGNED_TYPE r(0);
std::memcpy(&r,&x,sizeof(int));//Please ignore. Not the point of the question...
return r;
}
int main(int argc, char*argv[]) {
std::cout << "The answer is ... " <<
Freaky::copyThing<unsigned long>(10)<<std::endl;
return EXIT_SUCCESS;
}
样本输出(实际输出可能取决于字节序和整数大小):
The answer is .... 10
以下不会编译并抱怨实现的原型copyThing()
与类中声明的原型不匹配。
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <type_traits>
class Freaky {
public:
template<
typename UNSIGNED_TYPE,
typename std::enable_if<(sizeof(UNSIGNED_TYPE)>=sizeof(int)),int>::type X = 0
>
static UNSIGNED_TYPE copyThing(int x) ;
};
template<
typename UNSIGNED_TYPE,
typename std::enable_if<(sizeof(int)<=sizeof(UNSIGNED_TYPE)),int>::type X
>
UNSIGNED_TYPE Freaky::copyThing(int x) {
UNSIGNED_TYPE r(0);
std::memcpy(&r,&x,sizeof(int));//Please ignore. Not the point of the question...
return r;
}
int main(int argc, char*argv[]) {
std::cout << "The answer is ... " <<
Freaky::copyThing<unsigned long>(10)<<std::endl;
return EXIT_SUCCESS;
}
两者之间的唯一区别是在该实现sizeof(UNSIGNED_TYPE)>=sizeof(int)
中已替换为sizeof(int)<=sizeof(UNSIGNED_TYPE)
。
显然,这两个语句在语义上是等价的。我在哪里可以找到如何确定模板原型相等的正式定义?
这显然是某种程度的词汇等价而不是语义等价。