【发布时间】:2020-12-02 19:02:01
【问题描述】:
我正在学习一本 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不去那里。也许你的意思是把它放在cast()函数上? -
将
const关键字移动到const To cast(From value)会返回此错误:'this' argument to member function 'cast' has type 'const short_caster<int>' (aka 'const NarrowCaster<short, int>'), but function is not marked const -
我也试过用c++11和20标准编译,都不行。
-
你可以使用
To cast(From value) const {...}
标签: c++ templates types casting type-alias