【问题标题】:g++ expects an unqualified-id, but what is it expecting?g++ 期望一个不合格的 id,但它期望什么?
【发布时间】: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&lt;int&gt;' (aka 'const NarrowCaster&lt;short, int&gt;'), but function is not marked const
  • 我也试过用c++11和20标准编译,都不行。
  • 你可以使用To cast(From value) const {...}

标签: c++ templates types casting type-alias


【解决方案1】:
struct NarrowCaster const {...

const 跟在成员函数之后,这意味着该函数不会修改任何数据成员:

To cast(From value) const {...}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-04-01
    • 1970-01-01
    • 2022-11-11
    • 1970-01-01
    • 2021-01-25
    • 2013-11-26
    • 1970-01-01
    相关资源
    最近更新 更多