MSVC error C2971 for const wchar_t * as template argument - c++

I want to add some information about parameters in my program (type and convertation function). Name of parameters is const. I wrote some code for it, but it not compile in MSVC 2017 (on GCC or Clang is OK)
#include <iostream>
#include <string>
namespace params
{
constexpr wchar_t CLIENT_LOGIN[] = L"ClientLogin";
template<const wchar_t * ParamName>
struct convert_traits
{
};
template<>
struct convert_traits<CLIENT_LOGIN>
{
using ConvertType = unsigned long long;
static ConvertType convert(const std::wstring &str)
{
return std::stoull(str);
}
};
}
int main() {
std::cout << params::convert_traits<params::CLIENT_LOGIN>::convert(L"123.0") << std::endl;
return 0;
}
I receive errors:
main.cpp(15): error C2971: 'params::convert_traits': template parameter 'ParamName': 'params::CLIENT_LOGIN': a variable with non-static storage duration cannot be used as a non-type argument
main.cpp(10): note: see declaration of 'params::convert_traits'
main.cpp(6): note: see declaration of 'params::CLIENT_LOGIN'
main.cpp(26): error C2971: 'params::convert_traits': template parameter 'ParamName': 'params::CLIENT_LOGIN': a variable with non-static storage duration cannot be used as a non-type argument
main.cpp(10): note: see declaration of 'params::convert_traits'
main.cpp(6): note: see declaration of 'params::CLIENT_LOGIN'
and can't found a fix for MSVC.

Solved with
extern const wchar_t CLIENT_LOGIN[] = L"ClientLogin";
but not work if define it in header.

Related

Cannot compile variant visitor access on MSVC 19.28

I try to compile a personal project on Visual Studio 2019 (using MSVC 19.28 compiler) and I came accross a compilation error in the std::visit which I don't understand:
<source>(131): error C2653: '`global namespace'': is not a class or namespace name
C:/data/msvc/14.28.29914/include\type_traits(1493): note: see reference to function template instantiation 'auto CommandLineOptionsParser<CmdLineOpts>::register_callback::<lambda_1>::()::<lambda_1>::operator ()<const _First&>(_T1) const' being compiled
with
[
_First=bool CmdLineOpts::* ,
_T1=bool CmdLineOpts::* const &
]
C:/data/msvc/14.28.29914/include\variant(1654): note: see reference to alias template instantiation 'std::_Variant_visit_result_t<CommandLineOptionsParser<CmdLineOpts>::register_callback::<lambda_1>::()::<lambda_1>,const std::variant<bool CmdLineOpts::* >&>' being compiled
<source>(120): note: while compiling class template member function 'void CommandLineOptionsParser<CmdLineOpts>::register_callback(const CommandLineOption &,std::variant<bool CmdLineOpts::* >)'
<source>(83): note: see reference to function template instantiation 'void CommandLineOptionsParser<CmdLineOpts>::register_callback(const CommandLineOption &,std::variant<bool CmdLineOpts::* >)' being compiled
<source>(142): note: see reference to class template instantiation 'CommandLineOptionsParser<CmdLineOpts>' being compiled
<source>(123): error C2672: 'visit': no matching overloaded function found
<source>(131): error C2893: Failed to specialize function template 'unknown-type std::visit(_Callable &&,_Variants &&...)'
C:/data/msvc/14.28.29914/include\variant(1654): note: see declaration of 'std::visit'
<source>(131): note: With the following template arguments:
<source>(131): note: '_Callable=CommandLineOptionsParser<CmdLineOpts>::register_callback::<lambda_1>::()::<lambda_1>'
<source>(131): note: '_Variants={const std::variant<bool CmdLineOpts::* > &}'
<source>(131): note: '<unnamed-symbol>=void'
Compiler returned: 2
This code compiles fine with gcc.
I tested the code snippet from cppreference on std::visit and it compiles with MSVC, so I am not so sure what the issue here.
I simplified the code and reproduced the issue on godbolt
Here's the code
#include <algorithm>
#include <functional>
#include <iostream>
#include <map>
#include <memory>
#include <sstream>
#include <string>
#include <set>
#include <string_view>
#include <variant>
#include <type_traits>
using InvalidArgumentException = std::invalid_argument;
using CommandLineOption = std::string;
template <class Opts>
class CommandLineOptionsParser : Opts {
public:
using OptionType = std::variant<bool Opts::*>;
using CommandLineOptionWithValue = std::pair<CommandLineOption, OptionType>;
Opts parse(const char* argStr) {
// First register the callbacks
bool Opts::* pBool = &Opts::help;
register_callback("help", pBool);
for (auto& cbk : _callbacks) {
cbk.second(0, argStr);
}
return static_cast<Opts>(*this);
}
private:
using callback_t = std::function<void(int, const char *)>;
std::map<CommandLineOption, callback_t> _callbacks;
void register_callback(const CommandLineOption& commandLineOption, OptionType prop) {
_callbacks[commandLineOption] = [this, &commandLineOption, prop](int idx, const char * argv) {
if (std::string(argv) == commandLineOption) {
std::visit([](auto&& a) {
using T = std::decay_t<decltype(a)>;
if constexpr (std::is_same_v<T, bool Opts::*>) {
std::cout << "bool" << std::endl;
}
},
prop);
}
};
};
};
struct CmdLineOpts {
bool help{};
};
int main(int argc, const char* argv[])
{
CommandLineOptionsParser<CmdLineOpts> p;
CmdLineOpts cmdLineOptions = p.parse("opt1");
}
It seems MSVC is having difficulty synthesizing a lambda with a pointer-to-member argument in a template context.
I tried to simplify it to a MCVE, hopefully it captures the essence of the issue:
template<class T>
bool test(int T::* t) {
return [](int T::* x) {
return true;
}(t);
}
struct A {
int a;
};
int main() {
return test<A>(&A::a);
}
It fails to compile in MSVC C++20 mode (but not C++17) with a similar nonsensical error (link):
<source>(5): error C2653: '`global namespace'': is not a class or namespace name
<source>(13): note: see reference to function template instantiation 'bool test<A>(int A::* )' being compiled
<source>(5): error C2664: 'bool test::<lambda_1>::operator ()(A *) const': cannot convert argument 1 from 'int A::* ' to 'A *'
<source>(5): note: There is no context in which this conversion is possible
<source>(5): note: see declaration of 'test::<lambda_1>::operator ()'
I would suggest to report this to the vendor.
As a potential workaround can try extracting the lambda into a functor class with a templated operator(), it seems to compile (example).

Why this code snippet works with C++17 whereas the compiler complains when using C++11?

Why this code snippet works with C++17 whereas the compiler complains when using C++11(i.e https://godbolt.org/z/71G91P)?
Are there any potential problems with this code snippet?
#include<iostream>
class ctx
{
public:
int map_create(void*){std::cout << "haha" << std::endl; return 0;};
};
ctx obj;
typedef int (ctx::*ctx_mem_func)(void*);
template <ctx_mem_func func>
int regHelper(void*)
{
((&obj)->*func)(nullptr);
return 0;
}
constexpr ctx_mem_func testFunc = &ctx::map_create;
typedef int(*callBackFunc)(void*);
int reg(callBackFunc)
{
return 0;
}
int main()
{
reg(regHelper<testFunc>);
//But this expression is ok.
reg(regHelper<&ctx::map_create>);
std::cout << "this is a test" << std::endl;
}
Here are the error messages when using c++11(gun 10.0.2):
<source>: In function 'int main()':
<source>:30:28: error: no matches converting function 'regHelper' to type 'callBackFunc {aka int (*)(void*)}'
reg(regHelper<testFunc>);
^
<source>:13:5: note: candidate is: template<int (ctx::* func)(void*)> int regHelper(void*)
int regHelper(void*)
^
This is a difference between C++14 and C++17. Simplified:
int f();
template<int (&)()> struct S {};
constexpr auto& q = f;
using R = S<q>; // valid in C++17, invalid in C++14
The change is to Allow constant evaluation for all non-type template arguments, meaning that now a constexpr variable naming a function (member function, etc.) is permissible as an NTTP where previously only the actual name of the function was permitted.

Clang fails to initialize static const template member

In order to force the execution of a template method at program start one can initialize a static member with a static method. Then the method is run at program start for every instantiation of the template class:
#include <cstdio>
template<typename t, t value>
struct dummy_user_t {};
template<int i>
struct my_struct_t
{
static int s_value;
// "use" s_value so it's initialized
using value_user_t = dummy_user_t<const int&, s_value>;
static int method()
{
printf("Hello %i!\n", i);
return 0;
}
};
// initialize s_value with method() to run it at program start
template<int i>
int my_struct_t<i>::s_value {my_struct_t<i>::method()};
// instantiate my_struct_t
template struct my_struct_t<6>;
int main()
{
// nothing here
}
The output will be Hello 6!
This code compiles on all three major compilers but when you make s_value const it won't work in clang anymore (3.4 - 7.0) while still working in MSVC and GCC:
<source>:19:52: error: no member 'method' in 'my_struct_t<6>'; it has not yet been instantiated
const int my_struct_t<i>::s_value {my_struct_t<i>::method()};
^
<source>:10:51: note: in instantiation of static data member 'my_struct_t<6>::s_value' requested here
using value_user_t = dummy_user_t<const int&, s_value>;
^
<source>:21:17: note: in instantiation of template class 'my_struct_t<6>' requested here
template struct my_struct_t<6>;
^
<source>:11:16: note: not-yet-instantiated member is declared here
static int method()
^
1 error generated.
Try it out yourself:
With non const int: https://godbolt.org/z/m90bgS
With const int: https://godbolt.org/z/D3ywDq
What do you think? Is there any reason clang is rejecting this or is it a bug?

Using curly braces to value-initialize temporary as initializer to static data member causes error

This very simple code code gives an error in GCC 6.0:
template<class T>
struct S {
// error: cannot convert 'T' to 'const int' in initialization
static const int b = T{};
};
int main() {
}
Strangely, if I use regular braces instead (T()) then the code compiles. Is this a bug? The code compiles fine in clang.
The reason that T() works is because the compiler interprets it as a function declaration which takes no argument. The compiling would be done with just an explicit casting:
static const int b = (const int) T{};

How to pass inner typedef which is "int X::*" as template function parameter?

In this code, I want to pass the address of x.y as the template parameter typename Name::Type leValue.
#include <iostream>
using std::cout;
using std::endl;
struct X {
X() : y(123) {}
const int y;
};
template<typename Name, typename Name::Type leValue>
void print() { cout << *leValue << endl; }
struct Foo {
typedef int X::* Type;
};
int main() {
X x;
print<Foo, &x.y>(); // What is the right syntax here?
}
However, with gcc 4.7.2, I get the following errors:
source.cpp: In function 'int main()':
source.cpp:22:5: error: parse error in template argument list
source.cpp:22:22: error: no matching function for call to 'print()'
source.cpp:22:22: note: candidate is:
source.cpp:11:6: note: template void print()
source.cpp:11:6: note: template argument deduction/substitution failed:
source.cpp:22:22: error: template argument 2 is invalid
If I instead change the typedef to typedef int Type;, and the print call to print<Foo, 3>();, then it works. I tried several things by looking at the error messages, but could not get the syntax right. I have also searched here, and found some useful posts dealing with template classes, but none dealing with template functions. I tried using those answers but it did not help.
Could you please help me with this syntax, or explain to me what I should try doing next to fix this?
Is this close to what you're looking for?
#include <iostream>
using std::cout;
using std::endl;
struct X {
X() : y(123) {}
const int y;
};
template<typename Name, typename Type, Type Name::*Member>
void print(Type& obj) { cout << obj.*Member << endl; }
int main() {
X x;
print<X, const int, &X::y>(x);
}
The address of x.y is unknown in compile time. You can take a pointer to the member y as template argument, however, you have to pass the address of the object instance in run-time.
It works when you change it to an int because your allowed to pass const ints as template parameters. Templates will not let you pass values as arguments because they need to be resolved at compile time.