c++ - 如何修复 "array rvalue"无法使用 gcc-4.8 和 clang-3.7 进行编译的问题?

标签 c++ c++11 g++ initializer-list clang++

此代码片段至少需要标记 -std=c++Ox 才能使用 GCC-4.9 进行编译。
请参阅online compilation on gcc.godbolt.org .

template <typename T, int SIZE>
int foo (const T (&table) [SIZE])           // T = char
{
  return SIZE ? table[0] : 0;
}

template <typename T, int SIZE>
int bar (const T (&table) [SIZE])           // T = char *
{
    return SIZE ? table[0][0] : 0;
}

int main (int argc, char *argv[])
{
  return argc
       + foo( "foo" )
       + foo( {argv[0][0], argv[1][1]} )    // array rvalue
       + bar( {argv[0],    argv[1]   } );   // array rvalue
}

使用 GCC-4.9 ... GCC-6 可以很好地编译。
但使用以前的 GCC 版本和所有 Clang 版本都失败(最后测试的是 Clang-3.7.1)。


问题

  1. 需要更改哪些内容来解决该问题?
    (如果可能,仅调整 main() 主体)
  2. 有没有办法让代码兼容C++03?
    (再次强调,如果可能的话,仅在 main() 主体中)

GCC-4.8.2 输出

example.cpp: In function 'int main(int, char**)':
17 : error: no matching function for call to 'foo(<brace-enclosed initializer list>)'
+ foo( { argv[0][0], argv[1][1] } )
^
17 : note: candidate is:
2 : note: template<class T, int SIZE> int foo(const T (&)[SIZE])
int foo (const T (&table) [SIZE]) // T = char
^
2 : note: template argument deduction/substitution failed:
17 : note: couldn't deduce template parameter 'T'
+ foo( { argv[0][0], argv[1][1] } )
^
18 : error: no matching function for call to 'bar(<brace-enclosed initializer list>)'
+ bar( { argv[0], argv[1] } );
^
18 : note: candidate is:
8 : note: template<class T, int SIZE> int bar(const T (&)[SIZE])
int bar (const T (&table) [SIZE]) // T = char *
^
8 : note: template argument deduction/substitution failed:
18 : note: couldn't deduce template parameter 'T'
+ bar( { argv[0], argv[1] } );
^
Compilation failed

Clang-3.7.1 输出

17 : error: no matching function for call to 'foo'
+ foo( { argv[0][0], argv[1][1] } )
^~~
2 : note: candidate template ignored: couldn't infer template argument 'T'
int foo (const T (&table) [SIZE]) // T = char
^
18 : error: no matching function for call to 'bar'
+ bar( { argv[0], argv[1] } );
^~~
8 : note: candidate template ignored: couldn't infer template argument 'T'
int bar (const T (&table) [SIZE]) // T = char *
^
2 errors generated.
Compilation failed

最佳答案

您可以通过为 C++11 将创建的临时数组命名来使此代码与 C++03 兼容。

int main (int argc, char *argv[])
{
    const char il1[] = {argv[0][0], argv[1][1]};
    const char* const il2[] = { argv[0], argv[1] };
    return argc
        + foo( "foo" )
        + foo( il1 )
        + bar( il2 );
}

关于c++ - 如何修复 "array rvalue"无法使用 gcc-4.8 和 clang-3.7 进行编译的问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35759743/

相关文章:

c++ - C++1 1's std::string' 的底层表示是否保证有终止空字符?

c++ - 在 MFC 中使用发送消息最小化和恢复窗口

c++ - 将 Boost UBLAS blas-1 应用于矩阵

C++将csv读入vector,getline()问题

c++ - 在 Qt 中实现回调

c++11 - C++11 何时给出有关运算符优先级的警告?

c++ - 虚表解释

c++ - 在 c++14 lambda 表达式中捕获和移动 unique_ptr

c++ - 为什么 C++ 弃用警告打印两次?

c++ - basic_filebuf::underflow 错误读取文件与 ifstream on/proc/pid/stat