c++的新生,所以如果我混淆了我的术语,请原谅我。一直在阅读Stroustrup,他非常坚定地使用大括号-init-list语法来构造和初始化对象,我一直试图在我的研究中应用它。然而,在使用模板探索继承时,我遇到了一些奇怪的行为,到目前为止,我还无法在网上找到答案。以下是几个例子:
非模板示例:
class A {
int x;
public:
A(int x = 0) : x{ x } {}; // works as expected.
};
class B : public A {
int y;
public:
B(int x = 1, int y = 1) : A(x), y{ y } {}; // old syntax works obviously.
};模板示例,它无法使用下面的错误进行编译:
template<typename T>
class A {
T x;
public:
A(T x = 0) : x{ x } {}; // works as expected.
};
template<typename T>
class B : public A<T> {
T y;
public:
// Compilation fails on the following line (vs2015).
// Compiler has an issue with A<T>{ X }. Replacing {} with ()
// works as expected. Shouldn't it work with {} as well?
// B(T x = 1, T y = 1) : A<T>( x ), y{ y } {};
B(T x = 1, T y = 1) : A<T>{ x }, y{ y } {};
};错误:
Error C2059 syntax error: ','
Error C2334 unexpected token(s) preceding '{'; skipping apparent function body现在真正令我困惑的是,为什么下面的工作是有效的:
template<typename T>
class C : public A<T> {
using A_alias = A<T>;
T z;
public:
// Why does this workaround work while the expected syntax fails
// to compile?
C(T x = 2, T z = 2) : A_alias{ x }, z{ z } {};
};有谁能解释一下这里发生了什么事,我已经翻阅了整整一天,我找不到任何关于这方面的参考资料,而且搜索到目前为止一直没有结果,因为我不知道确切的搜索是什么。
发布于 2016-06-18 12:35:09
这看起来像一个编译器错误。gcc在--std=c++14级别编译所讨论的代码,没有问题。
https://stackoverflow.com/questions/37896876
复制相似问题