cpp*_*ner 11 c++ templates c++17 template-instantiation
此代码在 G++ 上运行,但不在 Visual C++ 上运行。
#include <iostream>
template<typename T> void foo( T& t,int some_parameter){}
template decltype(foo<int>) foo;
int main(){
std::cout << "Hello, world!\n";
}
Run Code Online (Sandbox Code Playgroud)
这是来自 Visual C++ 的错误:-
错误 C2206:“foo”:typedef 不能用于函数定义
激励:我不想为显式实例化重复函数签名。
我修改了/sf/answers/1984934871/ 中的代码。
哪一个是错的?如何在 Visual C++ 中解决它?
一天后,这是我找到的最佳解决方法:https : //stackoverflow.com/a/50350144。
#include <tuple>
template<typename... Ts>auto instantiate() {
static auto funcs = std::tuple_cat(std::make_tuple(
foo1<Ts>,
foo2<Ts>
)...);
return &funcs;
}
template auto instantiate<int, double>();
Run Code Online (Sandbox Code Playgroud)
但是,在 Visual C++ 中,它仅在foo.cpp启用优化的情况下进行编译时才有效:-
Custom或Disabled(/Od)不正常。/O1,/O2并/Ox 都OK。/Od, /O1,/O2和/Ox:-
/Og好。/Oi, /Ot, /Oy, /Ob2,/GF和/Gy是不行的。变通方法的变通方法(使用/Od):std::tuple_size<decltype(instantiate<int, double>())>在 .cpp 中调用内部的虚拟函数。然后在头文件中声明虚拟函数。
我相信msvc是错误的。简而言之,显式实例化template后面只是典型的声明。
如果你遵循语法[temp.explicit]
explicit-instantiation:
template declaration
declaration:
block-declaration
block-declaration:
simple-declaration
simple-declaration:
decl-specifier-seq init-declarator-list;
decl-specifier-seq:
decl-specifier
decl-specifier:
defining-type-specifier
defining-type-specifier:
simple-type-specifier
simple-type-specifier:
decltype-specifier
decltype-specifier:
decltype ( expression )
Run Code Online (Sandbox Code Playgroud)
我不相信有解决办法。显然,msvc 将其视为decltype类型别名,并拒绝任何具有别名签名的“感知”定义。这些也被拒绝
using F = decltype(foo<int>);
template F foo;
extern template F foo; // not even a definition
Run Code Online (Sandbox Code Playgroud)
但它接受这些
F bar;
decltype(foo<int>) baz;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
226 次 |
| 最近记录: |