模板参数中的"T"和"const T"有什么区别吗?
Is there any difference between "T" and "const T" in template parameter?
以下两种语法之间有什么区别吗:
template<int N> struct A; // (1)
和
template<const int N> struct A; // (2)
关于何时使用每种语法,有什么通用指南吗?
否。
§14.1 [temp.param] p5
[…]在确定其类型时,会忽略模板参数上的顶级cv限定符。
我在快速搜索标准时发现了这一点:
template<const short cs> class B { };
template<short s> void g(B<s>);
void k2() {
B<1> b;
g(b); // OK: cv-qualifiers are ignored on template parameter types
}
评论说他们被忽视了。
我建议不要在模板参数中使用const
,因为这是不必要的。请注意,它也不是"隐含的"——它们是常量表达式,与const
不同。
选择int
可能是个坏主意,但它对指针有影响:
class A
{
public:
int Counter;
};
A a;
template <A* a>
struct Coin
{
static void DoStuff()
{
++a->Counter; // won't compile if using const A* !!
}
};
Coin<&a>::DoStuff();
cout << a.Counter << endl;
相关文章:
- 向量 <int> a {N, 0} 和 int arr a[N] = {0} 的时间复杂度有什么区别
- 在 .h 文件中的类中声明静态变量和在.cpp文件中声明"global"变量有什么区别
- 我是C++编程的新手,这些代码之间有什么区别,我应该使用哪一个
- 返回常量对象引用 (getter) 和仅返回字符串有什么区别?
- Qt:remove() 和 rmdir() 有什么区别
- 这 4 个 lambda 表达式之间有什么区别?
- 将向量作为类>(值)<向量启动和向量<类>[值]有什么区别
- typedef 枚举和枚举类有什么区别?
- &C::c 和 &(C::c) 有什么区别?
- ascii 和 unicode 在处理级别有什么区别吗?
- C 中的常量限定符和 C++ 中的常量限定符有什么区别?
- "ABC" 和 "ABC" ) 在C++中有什么区别?
- 空指针常量 (nullptr)、空指针值和空成员指针值之间有什么区别?
- 引用捕获和在 lambda 中通过引用发送参数有什么区别 (C++)
- 两种访问I2C总线的方法有什么区别?
- 两种模板示例有什么区别?
- 这两种C++语法之间有什么区别?
- lua 5.0.2 模块和 5.3.5 有什么区别?
- C++中"typedef"、"using"、"namespace"和"using namespace"有什么区别?
- std::enable_if 和 std::enable_if_t 有什么区别?