Function template overload resolution fails in Visual C++ 2017 - c++

I am trying to figure out if what I wrote is legal C++14 w.r.t. unambiguous function template overload resolution.
In my opinion, the below program should compile and return 3.
Various versions of Clang and GCC compute just that at compile time (using -std=c++14 -O2), but Visual C++ 2017 (Version 15.5.2; latest update at time of writing) chokes on it with the below error message.
enum class Enum0 { State };
enum class Enum1 { State };
template <Enum0 Param0 = Enum0::State>
int get()
{
return 1;
}
template <Enum1 Param1>
int get()
{
return 2;
}
int main()
{
int sum = 0;
sum += get(); // should call instantiation of first function template
sum += get<Enum1::State>(); // should call instantiation of second function template
return sum;
}
This is the emitted error message by the Visual C++ compiler:
20 : <source>(20): error C2668: 'get': ambiguous call to overloaded function
11 : <source>(11): note: could be 'int get<Enum1::State>(void)'
5 : <source>(5): note: or 'int get<Enum0::State>(void)'
20 : <source>(20): note: while trying to match the argument list '()'
See https://godbolt.org/g/PhH2VY for a live demonstration (and https://godbolt.org/g/BVEv79 for the previous code example before editing the question).
Change the compiler to MVSC to see the compilation failing. GCC and Clang do not indicate any issue. Both nicely emit the following x86 assembly:
mov eax, 3
ret
Are GCC and Clang too lenient, or is this an issue with Visual C++?

That's a good question, isn't it. If I change the second call to get with:
sum += get<Enum1::State, int>(0.0); // should call instantiation of second function template
... then it compiles...
Notice, I add a second template argument. In my day to day work, I use an old dialect of C++ compatible with MFC...so take my reasoning with a grain of salt. But, since you are only providing one argument to the template, and the second template requires two arguments, ISTM that the VC++ compiler is trying to use the first template because it has default arguments and can take only one argument. So it chooses that template but cannot do the conversion from Enum1 to Enum0.

Related

Why does the compiler issue a template recursion error?

I'm currently trying to deduce a std::tuple type from several std::vectors that are passed as parameters. My code works fine using gcc, but the compilation fails with Visual Studio Professional 2019 with the message "fatal error C1202: recursive type or function dependency context too complex".
It has been mentioned for my previous post (C++ "fatal error C1202: recursive type or function dependency context too complex" in visual studio, but gcc compiles) that the problem is caused by template recursion as explained in C++ template compilation error - recursive type or function dependency. However, I don't see where the recursion occurs.
So my questions are:
Why is there an (infinite) recursion?
How can it be resolved?
Here is the code (I'm bound to C++11):
#include <tuple>
#include <vector>
template <typename TT,typename Add>
auto addTupBase(TT t,std::vector<Add> a) ->decltype (std::tuple_cat(t,std::make_tuple(a[0])))
{
return std::tuple_cat(t,std::make_tuple(a[0])) ;
}
template <typename TT,typename Add,typename... Args>
auto addTupBase(TT t,std::vector<Add> a,Args... args)-> decltype(addTupBase(addTupBase(t,a),args...))
{
return addTupBase(addTupBase(t,a),args...);
}
template <typename T,typename... Args>
auto addTup(std::vector<T> in,Args... args) ->decltype(addTupBase(std::make_tuple(in[0]),args...))
{
return addTupBase(std::make_tuple(in[0]),args...);
}
int main()
{
using TupleType = decltype(addTup(std::vector<char>{2},std::vector<int>{5},std::vector<double>{32423}));
TupleType t;
std::get<2>(t) = 342.2;
return 0;
}
MSVC has some conformance issues when running in /permissive mode and "The Microsoft C++ compiler doesn't currently support binding nondependent names when initially parsing a template. This doesn't conform to section 14.6.3 of the C++ 11 ISO specification. This can cause overloads declared after the template (but before the template is instantiated) to be seen.".
If you instead use /permissive- "The compiler [...] implements more of the requirements for two-phase name look-up" and will compile your program as-is.
Also note that you aren't actually using C++11. MSVC 19.24 supports C++14 and up.

How to specify template deduction guides for template aliases?

I am trying to make this code compile in VS 2019 (16.10.4) with /std:c++17. The following fails:
namespace my
{
template<class _Key, class _Compare = std::less<_Key>, class _Allocator = std::allocator<_Key>>
using Set = std::set<_Key, _Compare, _Allocator>;
}
void test()
{
std::set set1 = { 1, 2, 3 };
static_assert(std::is_same_v<std::set<int>, decltype(set1)>);
my::Set set2 = { 1, 2, 3 }; // Error here.
static_assert(std::is_same_v<my::Set<int>, decltype(set2)>);
}
with error:
error C2955: 'my::Set': use of alias template requires template argument list
message : see declaration of 'my::Set'
The same code compiles fine on godbolt with gcc -std=c++17 without any deduction guides. See sample.
Is there a way to make this compile on VS 2019 (16.10.4) with /std:c++17? My actual code is quite verbose. I created this minimal reproducible sample and it might just come down to solving this small piece. I also tried specifying deduction guides for my::Set but they have similar errors.
my::Set in your code is an alias template, and class template argument deduction for alias templates is a new feature of C++20: https://en.cppreference.com/w/cpp/compiler_support/20
Experimentally one can find that template argument deduction in this example is available in Visual Studio since version 16.11, please also specify /std:c++20 command-line option. Demo: https://gcc.godbolt.org/z/93jdvfPcn
The same code compiles fine on godbolt with gcc -std=c++17 without any deduction guides.
It is a bug in GCC that it allows class template argument deduction for alias templates in C++17 mode: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=103852

Couldn't deduce template parameter for Eigen::Matrix

When I try to compile the following function (forward) using MSVC 19.latest I get the following error message.
'Eigen::Matrix<float,ann_output_len<LayerNodeConfig...>::value,1,0,_Rows,1> forward(const
ArtificialNeuralNetwork<InputSize,LayerNodeConfig...> &,const Eigen::Matrix<float,Rows,1,0,_Rows,1> &)':
could not deduce template argument for 'const Eigen::Matrix<float,Rows,1,0,_Rows,1> &' from
'Eigen::Matrix<float,2,1,0,2,1>'
forward interface
template<int InputSize, int ... LayerNodeConfig>
auto forward(const ArtificialNeuralNetwork<InputSize, LayerNodeConfig...>& ann,
const RL::Arrayf<InputSize>& input)
-> typename ANN::output_t<LayerNodeConfig...>
In main function
RL::Arrayf<2> X;
auto Y = forward(sampling_policy, X);
Now what I don't understand is why can't the compiler substitute Rows and _Rows with 2.
Any insight is appreciated.
You can try the full code in godbolt.org using this link, https://godbolt.org/z/7Mj5ee and try to compile it yourself if you like.
Note: I tried to compile the same code with latest GCC compiler and it compiled.
Update - Mar 06, 2021:
I made a workaround by changing the interface of function forward to accept Eigen::DenseBase<Derived> instead of RL::Arrayf<InputSize>.
Anyone who is interested can read more about it here, https://eigen.tuxfamily.org/dox/TopicFunctionTakingEigenTypes.html

Template Alias, Variable Template, and auto type deduction failing to deduce template argument

While working on my class declaration I'm having some confusion on how to use alias templates and template variables within in a non class template while trying to use auto type deduction.
Signal.h
#ifndef SIGNAL_H
#define SIGNAL_H
#include <cstdint>
template<typename T>
using TimeSignal = T;
using DiscreteTime = TimeSignal<std::uint8_t>;
using ContinuousTime = TimeSignal<double>;
class Signal {
private:
template<typename T>
static TimeSignal<T> time_;
double voltage_;
double current_;
public:
template<typename T>
explicit Signal( TimeSignal<T> time, double voltage = 0, double current = 0 ) :
voltage_{voltage}, current_{current}
{ time_ = time; }
double sampleVoltage() { return voltage_; }
double sampleCurrent() { return current_; }
template<typename T>
static auto atTime() { return time_; }
};
#endif // SIGNAL_H
And I would be using it like this:
#include <iostream>
#include "Signal.h"
int main() {
DiscreteTime t1{ 5 };
ContinuousTime t2{ 7.5 };
Signal s1{ t1, 3.5, 0.05 );
Signal s2{ t2, 4.3, 0.09 );
auto time1 = s1.atTime();
auto time2 = s2.atTime();
return 0;
}
I don't want to template this class, so I was thinking about having an internal variable template. Outside of the class I was trying to use a template alias to have the different "TimeSignals" be descriptive as a "DiscreteTime" is typically and integral type and a ContinousTime is a floating point or over the set of Real numbers. I was however templating the constructor of this class that takes in the TimeSignal type and wanted the class to deduce the or to auto resolve it's internal variable template to that type depending which of the two types were passed in. Finally I was trying to use auto type deduction to return that type.
I don't know if its the syntax or the usage but this has me stumped. I'm not sure how to get this to a working compile state.
This is the current compiler errors that Visual Studio 2017 is giving me.
1>------ Build started: Project: Circuit Maker Simulator, Configuration: Debug x64 ------
1>main.cpp
1>c:\...\main.cpp(15): error C2672: 'Signal::atTime': no matching overloaded function found
1>c:\...\main.cpp(15): error C2783: 'auto Signal::atTime(void)': could not deduce template argument for 'T'
1>c:\...\Signal.h(64): note: see declaration of 'Signal::atTime'
1>c:\...\main.cpp(24): error C2672: 'Signal::atTime': no matching overloaded function found
1>c:\...\main.cpp(24): error C2783: 'auto Signal::atTime(void)': could not deduce template argument for 'T'
1>c:\...\Signal.h(64): note: see declaration of 'Signal::atTime'
1>Done building project "Circuit Maker Simulator.vcxproj" -- FAILED.
The compiler error's obvious to what they are saying, but it's like they are screaming or yelling at me without any help, assistance or suggestions on how to fix or resolve this...
Edit
User rafix07 helped me quite a bit with his answer and it was helpful. I was missing a couple of things, two of them I may have eventually caught onto if I kept staring at it long enough and that was the use of the variable templates within the class needing it's template argument or parameter. The other was using the scope resolution operator in the main function to call the static function. I could of found them given some time.
The one issue that had me stumbling in circles was the fact that I had to explicitly instantiate the function template of the type I want when calling it. This is the one that would of had me pulling out my hair for ours...
After adjusting the code according to the link in his answer I'm now able to compile, however I am now getting linker errors for unresolved external symbols and it has to do with the template variables. Which shouldn't be a problem, just need to define it within a cpp file to resolve static variables.
First of all, atTime is static method so only way to call it is to use scope resolution operator ::. atTime takes no arguments, so T cannot be deduced, and you need to put type in template arguments list explicitly:
auto time1 = Signal::atTime<DiscreteTime>();
auto time2 = Signal::atTime<ContinuousTime>();
In ctor of Signal and atTime function you have to specify T for which variable template is accessed:
template<typename T>
explicit Signal( TimeSignal<T> time, double voltage = 0, double current = 0 ) :
voltage_{voltage}, current_{current}
{ time_<T> = time; }
Full working code is here.

subtype reference argument compile error on gcc

I have a problem compiling a c++ program with gcc version 4.6.3; I can compile this program with microsoft compiler (v 9.0) without problems.
This program is using some of my libraries I always used with microsoft compiler.
problem is when I try to pass a reference as argument that is a subtype of another: pseudo example here:
class ObjManager{..}
class SubObjMng : public ObjManager{
public:
inline SubObjMng() : ObjManager(0, ... ){}
};
class Test{
public:
Test(int i, ObjManager &obj_mng);
}
int main(){
SubObjMng myobjmng;
Test t(0, myobjmng); //GCC ERROR HERE
}
output of the error is (real output for my program):
globals.h:227:40: error: no matching function for call to cdk::HashMap::HashMap(unsigned int, cdk::PtrObjMng, cdk::cstrObjMng)
globals.h:227:40: note: candidates are:
contrib/cdklib/cdk_struct.h:485:12: note: cdk::HashMap::HashMap(uint32_t, cdk::ObjManager&, cdk::ObjManager&)
contrib/cdklib/cdk_struct.h:485:12: note: no known conversion for argument 2 from cdk::PtrObjMng to cdk::ObjManager&
anyone can help?
thanks!
cdk::PtrObjMng should inherit from cdk::ObjMng, making polymorphism possible through references. Otherwise this is a no-go according to what the compiler says.
Of course this might not be the root of your problem, I wish we could see the implementation of your constructor.