LoginSignup
3
0

More than 5 years have passed since last update.

constexprラムダ式に関するコンパイル結果のメモ

Posted at

概要

関数の引数の型について、参照の有無によってg++とclang++のコンパイル結果が異なる。

コンパイラ

g++ 7.3.1
clang++ 6.0.0

コード1

#include <iostream>

template <typename T>
void func(T obj)
{
    constexpr char const* x = obj();
    std::cout << x << std::endl;
}

int main()
{
    func( []{ return "test"; } );
}
g++ OK
clang++ OK

コード2

#include <iostream>

template <typename T>
void func(T const& obj)
{
    constexpr char const* x = obj();
    std::cout << x << std::endl;
}

int main()
{
    func( []{ return "test"; } );
}
g++ OK
clang++ error: constexpr variable 'x' must be initialized by a constant expression

コード3

#include <iostream>

template <typename T>
void func(T&& obj)
{
    constexpr char const* x = obj();
    std::cout << x << std::endl;
}

int main()
{
    func( []{ return "test"; } );
}
g++ OK
clang++ error: constexpr variable 'x' must be initialized by a constant expression
3
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
0