gpt4 book ai didi

原型(prototype)的 C++ 模板等价性

转载 作者:行者123 更新时间:2023-11-30 03:52:03 25 4
gpt4 key购买 nike

以下编译按预期运行和执行:

#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() 的实现原型(prototype)与类中声明的不匹配。

#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)在该实现中。

显然这两个语句在语义上是等价的。在哪里可以找到关于如何确定模板原型(prototype)相等的正式定义?

这显然是某种程度的词汇对等,而不是语义对等。

最佳答案

我找不到标准的任何部分明确指定类模板(或成员的外联定义中的类模板及其说明符)的重新声明何时相同。

编译器实际上遵循 C++11 14.5.6.1/5+6 中指定的函数模板重新声明规则:

5 Two expressions involving template parameters are considered equivalent if two function definitions containing the expressions would satisfy the one definition rule (3.2), except [template parameter renaming]. 6 Two function template are equivalent if they are declared in the same scope, have the same name, have identical template parameter lists, and have return types and parameter lists that are equivalent using the rules described above to compare expressions involving template parameters.

不过,我找不到任何规则使它适用于非类型模板参数类型中的表达式,以重新声明类模板。

关于原型(prototype)的 C++ 模板等价性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30917253/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com