9

Why is the template version allowed to compile in gcc? Is it a compiler bug or is it actually valid when used with templates? Can someone explain this to me, please?

It does not compile on clang or other compilers used on godbolt.org.

The compile errors generates from both string and stringstream being used in a constexpr.

#include <iostream>
#include <string>
#include <sstream>

template<typename T>
constexpr std::string func1(T a, T b) //Compiles and runs
{
  std::stringstream ss;
  ss << a << b << a+b;
  return ss.str();
}

constexpr std::string func2(int a, int b) //Compile error
{
  std::stringstream ss;
  ss << a << b << a+b;
  return ss.str();
}

int main()
{
  int a = 5;
  int b = 7;
  std::cout << func1(a,b) << std::endl;
  return 0;
}
2
  • Note: Both clang and ICC reject this code. Commented Mar 21, 2017 at 11:44
  • It compiles from version gcc 4.6.4 and up to gcc 7 (snapshot). Commented Mar 21, 2017 at 11:47

1 Answer 1

9

GCC could be in the right here. According to dcl.constexpr paragraph 6:

If the instantiated template specialization of a constexpr function template or member function of a class template would fail to satisfy the requirements for a constexpr function or constexpr constructor, that specialization is still a constexpr function or constexpr constructor, even though a call to such a function cannot appear in a constant expression. If no specialization of the template would satisfy the requirements for a constexpr function or constexpr constructor when considered as a non-template function or constructor, the template is ill-formed, no diagnostic required.

The program is ill-formed (std::string is not a literal type) but it is not required to emit a diagnostic.

Sign up to request clarification or add additional context in comments.

2 Comments

Note that all compikers are compliant; no diagnostic required does not mean required no diagnostic.
Also, if we could just find one T for which the function really would be constexpr the code would be well formed. And the compiler is not required to sort that out.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.