如何解决g ++期望一个unqualified-id,但是它期望什么呢?
我正在学习一本c ++书中的类型别名的课程,并尝试编译以下代码:
#include <cstdio>
#include <stdexcept>
template <typename To,typename From>
struct NarrowCaster const { //first error points here
To cast(From value) {
const auto converted = static_cast<To>(value);
const auto backwards = static_cast<From>(converted);
if(value != backwards) throw std::runtime_error{ "Narrowed!" };
return converted;
}
};
template <typename From>
using short_caster = NarrowCaster<short,From>; //second error
int main(){
try {
const short_caster<int> caster;
const auto cyclic_short = caster.cast(142857); //third error
printf("cyclic_short: %d\n",cyclic_short);
}catch(const std::runtime_error& e) {
printf("Exception: %s\n",e.what());
}
}
不幸的是,g ++(或clang ++,因为我使用的是OS X)这样说:
typealias.cpp|5 col 27 error| expected unqualified-id
这似乎还会导致2个错误:
typealias.cpp|15 col 34 error| expected ';' after alias declaration
typealias.cpp|19 col 27 error| variable has incomplete type 'const short_caster<int>' (aka 'const NarrowCaster')
typealias.cpp|5 col 8 error| note: forward declaration of 'NarrowCaster'
我已经尝试解决此问题,我已经在使用std = c ++ 17,并检查了非ASCII字符,并确保与本书中的代码没有任何不同。我在做什么错了?
编译器命令,如果有帮助的话:
g++ typealias.cpp -o typealias -std=c++17
解决方法
struct NarrowCaster const {...
const
位于成员函数之后,这意味着该函数将不会修改任何数据成员:
To cast(From value) const {...}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。