列表初始化中多个模板构造函数的过载规则

Overload rules for multiple, templated constructors in list initialization

本文关键字:构造函数 规则 初始化 列表      更新时间:2023-10-16

我不确定以下代码是否根据C 11标准有效,并且在不同的实现中应具有相同的行为:

#include <cstddef>
struct Foo{
    template <std::size_t N>
    constexpr Foo( const char ( &other )[N] )       
    {}
    template <class T>
    constexpr Foo( const  T* const& other ) = delete;
};
struct Bar {
    Foo a;
    int b;
};
int main() {
    Bar bar{ "Hello",5};
}

一般的想法是允许字符串文字和 std::string的构造(此处未显示),而不是从指针到const char的构造,这有点棘手(在此问题中进行了讨论)。

g (> = 6.0)和几乎所有clang 版本(> = 3.4)的新版本似乎可以很好地编译,但是例如。使用g++-4.8 -std=c++11 main.cpp,我会收到以下错误:

main.cpp: In function ‘int main()’:
main.cpp:17:27: error: use of deleted function ‘constexpr Foo::Foo(const T* const&) [with T = char]’
     Bar bar{ "Hello",5};

所以我的问题是:
标准是否完全需要此代码的某些行为,如果是,谁是对的?

封闭了{}中的Intorizer为我工作,例如:

#include <cstddef>
struct Foo {
    template<std::size_t N>
    constexpr Foo(const char (&)[N]) {}
    template<class T>
    constexpr Foo(const T* const&) = delete;
};
struct Bar {
    Foo a;
    int b;
};
int main() {
    Bar bar{ {"Hello"}, 5 };
    //       ^^^^^^^^^
    (void)bar;
}

我用GCC 4.8.1在Wandbox上测试了它
https://wandbox.org/permlink/1tjf2nyt7mrkkqq0

GCC不一定不正确,我隐约记得有关此的缺陷报告。