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 {...}